import requests
from loguru import logger
from setting import Setting
from utils.py_object import cache
from utils.cases import is_cache_value


class HTTPAPIClient(object):

    def __init__(self):
        # 初始化session对象 ，他可以处理同一页面的cookies信息。
        self.client = requests.Session()

    def __del__(self):
        self.client.close()

    def get_url(self,path):
        return Setting().base_url + path

    # 请求所有的接口
    def request(self,path,**kwargs):
        # 判断是否能获取到cookies值
        cookies = cache.get('cookie_jar')
        if cookies is not None:
            res = self.client.request(url=self.get_url(path),cookies=cookies,**kwargs)
        else:
            res = self.client.request(url=self.get_url(path),**kwargs)
        return res.json()

    # 登录接口
    def login(self,login_info):
        res = self.client.request(url=self.get_url('/api/user/login'),method='post',json=login_info)
        return res

    def request_api(self,config_data):
        path = config_data.get('path')          # 请求地址
        method = config_data.get('method')      # 请求方法
        req_body = config_data.get('params')    # 请求体

        # 需要处理path中包含的变量
        path = get_path(path)

        # 对请求体参数进行判断 ，若包含{{}} ，则需要从缓存中提取
        if req_body is not None:
            for key,value in req_body.items():
                new_value = is_cache_value(value)
                if value != new_value:
                    req_body[key] = new_value       # 更新字典的值
        # 请求api接口
        actual_result = self.request(path,method=method,json=req_body)
        logger.info("请求的接口地址:{},请求体:{},响应结果:{}".format(path,req_body,actual_result))
        return actual_result


# 判断路径中是否包含变量
def get_path(path):
    """
    返回的真实路径
    :param path: /api/admin/user/delete/{{id}}
    :return: /api/admin/user/delete/415
    """
    start_index = path.find("{{")
    end_index = path.find("}}")
    if start_index >=0 and end_index >=0:
        new_value = cache.get(path[start_index+2:end_index])        # 从缓存中提取变量中的值
        logger.info("接口地址中包含变量，需要存缓存中提取，键名:{},值:{}".format(path[start_index+2:end_index],new_value))
        # 需要缓存带有变量的部分，比如：{{id}}
        old_value = path[start_index:end_index+2]
        # 进行接口字符串替换
        path = path.replace(old_value,str(new_value))
        logger.info("返回替换后的路径为:{}".format(path))
        return path
    return path



if __name__ == '__main__':
    http = HTTPAPIClient()
    print(http.login(Setting().login_info).json())
